<?php

namespace app\api\controller\agent;

use app\api\BaseController;
use think\facade\Db;
use WeChat\Contracts\Tools;

class TradeController extends BaseController
{
    /**
     * 微信回调
     * */

    public function wxNotify()
    {
        $result = Tools::xml2arr(file_get_contents('php://input'));
        if (!empty($result)) {
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                $this->changeTrade($result['out_trade_no']);

                echo '<xml>' .
                    '<return_code><![CDATA[SUCCESS]]></return_code>' .
                    '<return_msg><![CDATA[OK]]></return_msg>' .
                    '</xml>';
                exit();
            }
        }

    }

    /**
     * 支付宝回调
     * */
    public function aliNotify()
    {
        $post = $_POST;
        if (!empty($post)) {
            if ($post['trade_status'] == 'TRADE_SUCCESS') {
                $this->changeTrade($post['out_trade_no']);
                echo 'success';
            }
        }
    }

    public function changeTrade($out_trade_no)
    {
        $rst = Db::name('agent_trade_order')->where('order_no', $out_trade_no)->where('status', 1)->find();
        if (!empty($rst)) {
            Db::name('agent_trade_order')->where('id', $rst['id'])->update(['status' => 2, 'update_time' => time()]);
            Db::name('agent_area')->insert(['store_id' => $rst['store_id'], 'uid' => $rst['uid'], 'type' => 4, 'status' => 2,
                'pid' => $rst['code'], 'create_time' => time(), 'update_time' => time(),
            ]);
            Db::name('user')->where('user_id', $rst['uid'])->update(['is_agent' => 4]);
            Db::name('finance')->insert(['uid' => $rst['uid'], 'money' => $rst['money'],
                'f_type' => 1, 'status' => 2, 'desc' => '购买vip代理', 'source' => $rst['id'], 'create_time' => time(),
            ]);
        }
    }
}
